

import 'package:moonplay/pages/common_page/common_text_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:moonplay/common/app_common.dart';
import 'package:moonplay/model/index_banner_model.dart';
import 'package:moonplay/model/recommend_model.dart';
import 'package:moonplay/utils/common_utils.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../utils/image_utils.dart';

class RecommendPage extends StatefulWidget {
  @override
  _RecommendPageState createState() => _RecommendPageState();
}

class _RecommendPageState extends State<RecommendPage> with AutomaticKeepAliveClientMixin {
  bool get wantKeepAlive => true;
  RecommendModel recommendModel;
  Future _futureBuilderFuture;
  IndexBannerModel indexBannerModel;
  RefreshController _refreshController = RefreshController(initialRefresh: false);

  // String errorImgUrl = "https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2596164201.jpg";

  @override
  void initState() {
    super.initState();
    init();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:
      commonFutureBuilder(
        context,
        future: _futureBuilderFuture,
        callWidget: recommendModel!=null ? bodyWidget() : Container(),
        callTap: init
      ),
    );
  }

  Widget bodyWidget(){
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,  //开启下拉刷新
      enablePullUp: false,    //开启上拉加载
      child: buildCtn(),
      onRefresh: () async {
        await _initGetList();
        _refreshController.refreshCompleted();
      }
    );
  }

  Widget buildCtn(){
    return CustomScrollView(
      reverse: false,
      slivers: _widgetLists()
    );
  }

  Widget _widgetSwiper(){
    return Container(
      height: ScreenUtil().getWidthPx(360),
      child: Swiper(
        autoplay: true,
        loop: true,
        itemBuilder: (BuildContext context,int index){
          return InkResponse(
            onTap: (){
              Get.toNamed('/VideoDetailPage', arguments: {"vodId": indexBannerModel.records[index].vodId, "typeId1": 20});
            },
            child: Container(
              child: loadNetworkImage('${indexBannerModel.records[index].vodPicSlide}', fit: BoxFit.fill),
            ),
          );
        },
        itemCount: indexBannerModel.records.length,
      )
    );
  }

  List<Widget> _widgetLists(){
    List<Widget> _list = [];
      
    Widget _addSwiper = SliverStickyHeader(
      header: Container(),
      sliver: SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, i) => Container(
            child: _widgetSwiper(),
          ),
          childCount: 1,
        ),
      ),
    );
    _list.add(_addSwiper);
    for (var i = 0; i < recommendModel.itemData.length; i++) {
      Widget _addWidget = SliverStickyHeader(
        header: Container(
          height: ScreenUtil().getWidthPx(80),
          padding: EdgeInsets.only(left: ScreenUtil().getWidthPx(10)),
          color: Colors.white,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Cmtext('${recommendModel.itemData[i].typeName}'),
              // InkResponse(
              //   onTap: (){
              //     print('点击更多');
              //   },
              //   child: Container(
              //     width: ScreenUtil().getWidthPx(140),
              //     height: double.infinity,
              //     padding: EdgeInsets.only(right: ScreenUtil().getWidthPx(10)),
              //     alignment: Alignment.centerRight,
              //     child: Row(
              //       mainAxisAlignment: MainAxisAlignment.end,
              //       children: <Widget>[
              //         Cmtext('更多', style: TextStyle(fontSize: 14, color: Theme.of(context).cardColor),),
              //         Icon(IconData(0xe635, fontFamily: Constants.IconFontFamily),color: Theme.of(context).cardColor, size: 16),
              //       ],
              //     ),
              //   ),
              // )
            ],
          ),
        ),
        sliver: SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 4),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              //横轴元素个数
              crossAxisCount: 3,
              //纵轴间距
              mainAxisSpacing: 3.0,
              //横轴间距
              crossAxisSpacing: 3.0,
              //子组件宽高长度比例
              childAspectRatio: 0.6
            ),
            delegate: SliverChildBuilderDelegate(
              (context, idx) => InkResponse(
                highlightColor: Colors.transparent,
                radius: 0,
                onTap: (){
                  Get.toNamed('/VideoDetailPage', arguments: {"vodId": recommendModel.itemData[i].itemList.records[idx].vodId, "typeId1": i+1});
                },
                child: Container(
                  child: Stack(
                    children: <Widget>[
                      Container(
                        height: double.infinity,
                        child: Column(
                          children: <Widget>[
                            Container(
                              height: ScreenUtil.getInstance().screenWidth / 3 / 0.75,
                              child: Stack(
                                children: <Widget>[
                                  // Container(
                                  //   width: double.infinity,
                                  //   height: ScreenUtil.getInstance().screenWidth / 3 / 0.75,
                                  //   decoration: BoxDecoration(
                                  //     borderRadius: BorderRadius.all(Radius.circular(4)),
                                  //     image: new DecorationImage(//背景图片
                                  //       image: NetworkImage(recommendModel.itemData[i].itemList.records[idx].vodPic),
                                  //       fit: BoxFit.cover
                                  //     ),
                                  //   ),
                                  // ),
                                  Positioned(
                                    top: 0,
                                    left: 0,
                                    right: 0,
                                    bottom: 0,
                                    child: Container(
                                      width: double.infinity,
                                      height: ScreenUtil.getInstance().screenWidth / 3 / 0.75,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.all(Radius.circular(4)),
                                      ),
                                      child: loadNetworkImage(recommendModel.itemData[i].itemList.records[idx].vodPic),
                                    ),
                                  ),
                                  Positioned(
                                    bottom: 0,
                                    left: 0,
                                    right: 0,
                                    child: Container(
                                      height: ScreenUtil().getWidthPx(60),
                                      alignment: Alignment.centerLeft,
                                      padding: EdgeInsets.only(left: ScreenUtil().getWidthPx(10)),
                                      decoration: BoxDecoration(
                                        color: Color.fromRGBO(0, 0, 0, 0.7),
                                        borderRadius: BorderRadius.only(bottomLeft: Radius.circular(4), bottomRight: Radius.circular(4))
                                      ),
                                      child: Cmtext('${recommendModel.itemData[i].itemList.records[idx].vodRemarks}', style: TextStyle(color: Colors.white, fontSize: 11), overflow: TextOverflow.ellipsis,),
                                    )
                                  )
                                ],
                              ),
                            ),
                            Expanded(
                              child: Container(
                                alignment: Alignment.center,
                                child: Cmtext('${recommendModel.itemData[i].itemList.records[idx].vodName}', style: TextStyle(fontSize: 13), overflow: TextOverflow.ellipsis,),
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  )
                ),
              ),
              childCount: recommendModel.itemData[i].itemList.records.length,
            ),
          ),
        )
      );
      _list.add(_addWidget);
    }
    
    return _list;
  }


  //网络初始化
  init(){
    setState(() {
      _futureBuilderFuture = _initGetList();
    });
  }

  Future _initGetList() async {
    return Future.wait<dynamic>([
      initGetIndex(),
      initSwiper()
    ]);
  }

  /**
   * 网络请求
   */
  initGetIndex() async {
    Map<String, dynamic> postData = {
      
    };
    var _res = await HttpUtil().request("queryAppIndex", data: postData, need_login: false);
    if(_res != null && _res['code'] == 200) {
      RecommendModel _list = RecommendModel.fromJson(_res['data']);
      for (var d = 0; d < _list.itemData.length; d++) {
        for (var i = 0; i < _list.itemData[d].itemList.records.length; i++) {
          var vodPic = _list.itemData[d].itemList.records[i].vodPic;
          if (vodPic != "" && vodPic.substring(0, 6) == "upload") {
            _list.itemData[d].itemList.records[i].vodPic = "http://app.ydecai.cn/" + _list.itemData[d].itemList.records[i].vodPic;
          }
        }
      }
        
      setState(() {
        recommendModel = _list;
      });
    }
    return _res;
  }

  initSwiper() async {
    var _res = await HttpUtil().request('getVideoSwiperList', need_login: false);
    if(_res != null && _res['code'] == 200) {
      setState(() {
        indexBannerModel = IndexBannerModel.fromJson(_res['data']);
      });
    }
    return _res;
  }
}
